package com.project.springboot.acu;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * description: 该反射工具类不明觉厉，但是代码看起来还算不错
 * @author 朱正磊
 * @date 2025-05-16 13:40:00
 */
public class ReflectTool {

    // 注册类型转换器的映射表
    private static final Map<Class<?>, Function<Object, String>> CONVERTERS = new HashMap<>();

    static {
        // 基本类型和包装类的处理
        CONVERTERS.put(String.class, obj -> ((String) obj).toString());
        CONVERTERS.put(Integer.class, obj -> ((Integer) obj).toString());
        CONVERTERS.put(Byte.class, obj -> ((Byte) obj).toString());
        CONVERTERS.put(Long.class, obj -> ((Long) obj).toString());
        CONVERTERS.put(Double.class, obj -> ((Double) obj).toString());
        CONVERTERS.put(Float.class, obj -> ((Float) obj).toString());
        CONVERTERS.put(Character.class, obj -> ((Character) obj).toString());
        CONVERTERS.put(Short.class, obj -> ((Short) obj).toString());
        CONVERTERS.put(Boolean.class, obj -> ((Boolean) obj).toString());

        // 大数类型处理
        CONVERTERS.put(BigDecimal.class, obj -> ((BigDecimal) obj).toString());
        CONVERTERS.put(BigInteger.class, obj -> ((BigInteger) obj).toString());

        // 日期类型处理（示例使用默认格式，实际应自定义）
        CONVERTERS.put(Date.class, obj -> ((Date) obj).toString());
    }

    public static String getReturnTypePrimitiveContent(Method method, Object obj) {
        if (obj == null) {
            return null;
        }

        // 处理基本类型
        if (method.getReturnType().isPrimitive()) {
            return String.valueOf(obj);
        }

        // 从映射表中查找对应的转换器
        Function<Object, String> converter = CONVERTERS.get(method.getReturnType());
        if (converter != null) {
            try {
                return converter.apply(obj);
            } catch (ClassCastException e) {
                // 记录日志或抛出异常
                System.err.println("类型转换错误: " + e.getMessage());
                return null;
            }
        }

        // 未知类型返回null
        return null;
    }

}
